<?php

namespace App\Http\Controllers\Admin;

use App\Model\ShopAttrTypeModel;
use Validator;
use Illuminate\Http\Request;
use App\Model\AdminLogsModel;
use App\Model\ShopAttrKeyModel;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;

class ShopAttrKeyController extends Controller
{
    //列表页
    public function index(Request $request)
    {	
    	//dd('aaaa');
    	$list = ShopAttrKeyModel::where(function ($query) {
		  if (request()->keywords) {
			  $query->where('kname', request()->keywords);
		  }
	  	})
		  ->orderBy('id', 'desc')
		  ->paginate(10);
	  	$pageParam['keywords'] = $request->input('keywords');

       	$page = $list->appends($pageParam)->links();
      	return view('admin.attr_key.index',compact('list','page','request'));
    }

    //加载添加页
    public function add()
    {
    	return view('admin.attr_key.add');
    }

    //添加
    public function insert(Request $request)
    {	
    	$post = $request->post();
	  	$validator = Validator::make($post,[
			'kname'=>'required|unique:shop_attr_key,kname',
		  
	  	],[
			'kname.required' => '规格名不能为空',
			'kname.unique' => '规格名已存在',
		 
	  	]);
	  	if($validator->fails()){
			return returnJson(0, $validator->errors()->first());
	  	}

	  	DB::beginTransaction();
	  	try {
			$attrkey = New ShopAttrKeyModel();
			$attrkey -> kname = request() -> kname;
			$attrkey -> save();
			DB::commit();
			$msg = '添加规格:【'.request()->kname.'】(id:'.$attrkey['id'].')';
			AdminLogsModel::addLog($msg);
	  	} catch (Exception $e) {
			DB::rollBack();
			throw $e;
			return returnJson(0,'操作失败,请稍后再试');
	  	}
	  	return returnJson(1,'添加成功');
    }

    //编辑页面
	public function edit(Request $request)
	{
  	    $list = ShopAttrKeyModel::where('id',request()->id)->first();
  	    return view('admin.attr_key.edit',compact('list'));
	}

	//修改
	public function update(Request $request)
	{	
			
		$post = $request->post();
	  	$validator = Validator::make($post,[
			'kname'=>'required|unique:shop_attr_key,kname',
		  
	  	],[
			'kname.required' => '规格名不能为空',
			'kname.unique' => '规格名已存在',
		 
	  	]);
	  	if($validator->fails()){
			return returnJson(0, $validator->errors()->first());
	  	}
	  	$list = ShopAttrKeyModel::where('id',$post['id'])->first();
	  	if(ShopAttrKeyModel::where('id',$post['id'])->update(['kname'=>request()->kname])){
			$msg = '规格【'.$list->kname.'】(id:'.$post['id'].'),更改规格名为:'.request()->kname;
			AdminLogsModel::addLog($msg);
			return returnJson(1, '修改成功');
		}else{
			return returnJson(0, '修改失败');
		}

	}
}
